import create from '../../../utils/create2.js'
import store from '../../../store/index.js'
import SessionUserUtil, {
  SessionUser
} from '../../../data/session/sessionUser.js';
import SessionSellingServerUtil from '../../../data/session/sessionSellingServer.js';
import SellingServerUtil from '../../../data/sellingServer.js';
const Common = require('../../../utils/common.js');
import InteractionUtil from '../../../shell/ui/interaction.js';
import LangUtil from '../../../utils/lang.js';
let ApiUrl = getApp().data.ApiUrl;
let modal;
create(store, {
  data: {
    token: "",
    userName: "",
    isHideAdd: true,
    oldCode: '',
    newCode: '',
    note: 0,
    notel: 0,
    if_show_card: false,
    activeVCardIndex: 0,
    showLogout: false,
    points: {},
    couponNum: 0,
    userInfo: {},
    isMember: false,
    level: 0,
    showMember: false,
    member: {},
    version: 0,
    logined: false,
    saleTypes: {},
    saleType: 1,
    btnText: '确认',
    tips: '确认切换为批发商城',
    loginUser: {}
  },
  onLoad: function (options) {
    SessionUserUtil.renewCache().then(sessionUser => {
      let saleType = sessionUser.salesModelType
      this.store.data.saleType = saleType
      this.setData({saleType})
      this.update()
    })
    this.updateTheme()
    wx.removeStorageSync('tagValue');
    wx.removeStorageSync('specialString');
    wx.removeStorageSync('checkedlis');
    wx.setNavigationBarTitle({
      title: '个人中心',
    });
    wx.setPageStyle();
    this.getCenterInfo();
    this.store.data.coupon = {}
    this.update()
    modal = this.selectComponent('#modal')
  },
  onShow: function () {
    this.queryLevel()
    wx.removeStorageSync('tagValue');
    wx.removeStorageSync('specialString');
    SessionUserUtil.getInstance().then(sessionUser => {
      if (sessionUser.userId <= 0) {
        // 强制登录
        wx.navigateTo({
          url: `/pages/my/logintype/logintype?from=userCenter`,
        })
      } else {
        let lang = {
          vcard_slogn : LangUtil.translate('vcard_slogn'),
          buy_goods : LangUtil.translate('buy_goods'),
          shopping_points : LangUtil.translate('shopping_points'),
          shopping_points_unit : LangUtil.translate('shopping_points_unit'),
        }
        this.setData({
          lang
        })
        console.log('my index this.data', this.data)
        // 页面数据初始化
        this.pageInitialize()
      }
    })

  },
  onHide: function () {
    this.setData({
      changetoguest: false
    })
  },
  getCenterInfo() {
    var page = this;
    Common.my_request({
      url: '/AppMaster/Index/userCenter',
      success: res => {
        if (res.data.result === 0) {
          const data = res.data.data;
          const {
            member,
            sale_type_switch
          } = data
          const {
            is_use_member,
            account_lv
          } = member
          page.setData({
            orderCount: data.order_count.length > 0 && data.order_count[0],
            servicePhone: data.service_phone,
            points: data.points,
            couponNum: data.coupon.num,
            isMember: is_use_member,
            level: account_lv,
            saleTypes: sale_type_switch
          })
          let {
            user
          } = this.store.data
          Object.assign(user, member)
          // this.store.data.saleType = sale_type_switch.sale_type_switch_button * 1 === 11 ? 1 : 2
          this.store.data.user = user
          this.update()
          this.updateTheme()
        } else {
          console.log(res)
        }
      }
    })
  },

  goAllOrders(e) {
    const id = e.currentTarget.id;
    if (wx.getStorageSync('user_id') < 0) {
      wx.navigateTo({
        url: '/pages/my/logintype/logintype?from=5&fromMy=' + id,
      });
    } else {
      wx.navigateTo({
        url: '/pages/order/index/index?fromMy=' + id,
      })
    }
  },

  // 顾问列表
  showConlist: function () {
    SellingServerUtil.getAccessibleServers().then(servers => {
      let allVCards = [],
        sessionSellingServer = SessionSellingServerUtil.getInstanceSync(),
        activeVCardIndex = 0
      servers.forEach(function (server, index) {
        let vCard = server.getTheVCardSync()
        allVCards.push({
          salesmanId: server.salesmanId,
          vCardId: vCard.id,
          name: vCard.name,
          contactPhone: vCard.contactPhone,
          avatarUri: vCard.avatarUri,
          introduction: vCard.introduction,
          tags: vCard.tags
        })
        if (sessionSellingServer.salesmanId === server.salesmanId) {
          activeVCardIndex = index
        }
      })
      this.setData({
        activeVCard: allVCards[activeVCardIndex],
        activeVCardIndex: activeVCardIndex,
        allVCards: allVCards
      })
    })
  },
  call() {
    var page = this;
    var servicePhone = page.data.servicePhone;
    wx.makePhoneCall({
      phoneNumber: servicePhone,
      success: function (res) {},
      fail: function (res) {}
    })
  },
  goGiff() {
    wx.navigateTo({
      url: '/subPage/giff/index',
    })
  },
  // 显示--隐藏我的顾问卡片
  showCard_toggle: function () {
    this.setData({
      if_show_card: !this.data.if_show_card
    })
  },
  // 滑动起始点
  my_start: function (e) {
    var page = this;
    page.setData({
      startPoint: e.touches[0].clientX
    })
  },
  // 滑动结束点--改变顾问列表的
  my_end: function (e) {
    var page = this;
    var startPoint = page.data.startPoint;
    var endPoint = e.changedTouches[0].clientX;
    var distance = startPoint - endPoint;
    var length = page.data.allVCards.length;
    var vCardIndex = page.data.activeVCardIndex;
    if (Math.abs(distance) > 30) {
      if (distance > 0) {
        /**向右滑 */
        if (vCardIndex + 1 >= length) {
          /** 滑到最后一个 */
          vCardIndex = 0;
        } else {
          vCardIndex++
        }
      } else {
        /**向左滑 */
        if (vCardIndex <= 0) {
          /** 滑到第一个 */
          vCardIndex = length - 1;
        } else {
          vCardIndex--
        }
      }
      page.setData({
        activeVCard: page.data.allVCards[vCardIndex],
        activeVCardIndex: vCardIndex
      })
    }
  },
  // 切换顾问
  changeConsulant: function (e) {
    let newServerId = e.currentTarget.id
    if (newServerId == SessionSellingServerUtil.getInstanceSync().salesmanId) {
      this.showCard_toggle()
      return
    }
    SessionSellingServerUtil.switchSellingServer(newServerId).then(message => {
      wx.showToast({
        title: message ? message : '顾问切换成功',
        duration: 2000
      })
      Common.when_user_change_clear_the_storage();
      setTimeout(function () {
        wx.reLaunch({
          url: '/pages/index/index'
        })
      }, 500)
    }).catch(error => {
      console.log(error.message, error)
      wx.showToast({
        title: error.message,
        image: '/pages/imges/fail.png',
        duration: 2000
      })
    })
  },
  coupon: function () {
    if (wx.getStorageSync('user_id') < 0) {
      wx.navigateTo({
        url: '/pages/my/logintype/logintype?from=2'
      });
    } else {
      wx.navigateTo({
        url: '/pages/coupon/index/index'
      })
    }
  },
  login: function () {
    wx.navigateTo({
      url: '/pages/my/logintype/logintype?from=4'
    });
  },
  loginchange: function () {
    wx.navigateTo({
      url: '/pages/my/logintype/logintype?from=7'
    });
  },

  getnickName() {
    var page = this;
    wx.getSetting({
      success(res) {
        /**拒绝过用户信息授权，点击打开授权设置页面 */
        if (res.authSetting['scope.userInfo'] == false) {
          wx.authorize({
            scope: 'scope.userInfo',
            success(res) {
              console.log(res.errMsg); //用户授权后执行方法，如果用户之前拒绝过授权，再次调用authorize就不会进success，直接进fail
            },
            fail(res) { //用户拒绝授权后执行
              wx.showModal({
                title: '提示',
                content: '需要您授权用户信息，是否跳转到用户信息授权设置页面',
                success: function (res) {
                  if (res.confirm) {
                    wx.openSetting({
                      success: function () {
                        SessionUserUtil.getInstance().then(sessionUser => {
                          page.setData({
                            nickname: sessionUser.nickname,
                            avatarUrl: sessionUser.avatarUrl
                          })
                        })
                      },
                      fail: function (data) {
                        Common.Alert("提示", "授权失败，请重新授权！");
                      }
                    });
                  } else if (res.cancel) {
                    console.log('用户取消跳到授权设置页面')
                  }
                }
              })
            }
          })
          return false;
        } else if (res.authSetting['scope.userInfo']) { //没有触发用户授权
          page.setData({
            nickname: data.nickName,
            avatarUrl: data.avatarUrl
          })
        }
      },
      fail(res) {
        console.log('调用失败')
      }
    })
  },

  /**
   * 退出登录
   */
  signOut: function () {
    Common.my_request({
      url: 'AppMaster/Login/vipLogout',
      success: function (res) {
        wx.removeStorageSync('token');
        Common.when_user_change_clear_the_storage();
        wx.removeStorageSync('consultantId');
        wx.setStorageSync('signOut', '1');
        SessionUserUtil.renewCache().then(() => {
          return SessionSellingServerUtil.renewCache()
        }).then(() => {
          wx.reLaunch({
            url: '/pages/index/index',
          });
        })

      }
    });
  },
  /**
   * 页面数据初始化操作
   * 
   * @returns {Promise<undefined>} 
   */
  pageInitialize: function () {
    return SessionUserUtil.getInstance().then(sessionUser => {
      // 处理依赖于SessionUser的待渲染数据
      let assignData = {
        user_type: sessionUser.accountType,
        isConsultant: sessionUser.isSalesman,
        consultantId: sessionUser.vCardId,
        user_id: sessionUser.userId,
        is_none_user_img: sessionUser.notSetAvatar,
        is_none_user_name: sessionUser.notSetName
      }
      if (sessionUser.userId > 0) {
        assignData.logined = 'true'
        if (sessionUser.phoneNumber) {
          assignData.userName = sessionUser.phoneNumber
          assignData.showNumber = true
        } else {
          assignData.showNumber = false
        }
        assignData.userinfo = {
          nickName: sessionUser.showName,
          realName: sessionUser.realName,
          avatarUrl: sessionUser.avatarUrl,
          mobile: sessionUser.phoneNumber
        };
        this.setData(assignData)

        // 做一些store模块相关的赋值操作
        // todo 需要考虑移除
        const {
          user
        } = this.store.data
        Object.assign(user, assignData.userinfo)
        this.store.data.user = user
        this.update()
        // 获取我的顾问列表
        this.showConlist()
      }
    }).then(() => {
      // 检测是否微信授权，用于展示获取授权的按钮
      return new Promise((resolve) => {
        wx.getSetting({
          success: (res) => {
            if (res.authSetting['scope.userInfo']) {
              resolve(true)
            } else {
              resolve(false)
            }
          }
        })
      })
    }).then((authorized) => {
      this.setData({
        is_authorized: authorized
      })
      // 处理其他事情
      let if_refresh = wx.getStorageSync("if_refresh");
      if (if_refresh == 3) {
        // wx.setStorageSync("if_refresh", 1);
      } else if (if_refresh == 2) {
        wx.setStorageSync("if_refresh", 3);
      }
      this.getCenterInfo();
    })
  },
  onGotUserInfo(e) {
    if (typeof e.detail.userInfo !== 'object') {
      wx.showToast({
        title: '请授权小程序读取您的昵称和头像信息！',
        icon: 'none',
        duration: 3000
      })
      return
    }
    let page = this,
      wxUserInfo = e.detail.userInfo,
      sessionUser = SessionUserUtil.getInstanceSync()
    // 授权后更新页面中记录的授权状态
    page.setData({
      is_authorized: true
    })
    // 执行更新操作
    sessionUser.nickname = wxUserInfo.nickName
    sessionUser.avatarUrl = wxUserInfo.avatarUrl
    console.log(sessionUser)
    SessionUserUtil.doUpdate(sessionUser).then(() => {
      this.pageInitialize()
    })
  },
  /**
   * 更新用户信息
   * 
   * @param {object} newUserInfo 待更改的用户信息
   * @returns {Promise<SessionUser>}
   */
  updateUserInfo(newUserInfo) {
    let newData = {}
    if (newUserInfo.avatarUrl) newData.user_img = newUserInfo.avatarUrl
    if (newUserInfo.realName) newData.real_name = newUserInfo.realName
    return new Promise((resolve, reject) => {
      if (Object.keys(newData).length === 0) {
        resolve()
        return
      }
      Common.my_request({
        url: '/AppMaster/Account/updateAccountInfo',
        data: newData,
        success: function (res) {
          if (res.data.result == 0) {
            resolve(res.data)
          } else {
            reject(res.data)
          }
        }
      })
    }).then(res => {
      return SessionUserUtil.renewCache()
    })
  },
  modify: function () {
    var page = this;
    page.setData({
      isHideAdd: !page.data.isHideAdd
    });
  },
  oldCodes: function (e) {
    //console.log(e.detail.value)
    this.setData({
      oldCode: e.detail.value
    })
  },
  newCodes: function (e) {
    //console.log(e.detail.value)
    this.setData({
      newCode: e.detail.value
    })
  },
  address_modify: function () {
    if (wx.getStorageSync('user_id') < 0) {
      wx.navigateTo({
        url: '/pages/my/logintype/logintype?from=3'
      });
    } else {
      wx.navigateTo({
        url: '/pages/my/address/address'
      })
    }
  },
  /**去登录处理 */
  LogIns: function () {
    wx.navigateTo({
      // url: "/pages/login/login?source=1"
      url: '/pages/my/logintype/logintype'
    })
  },
  modifyPassword: function () {
    var page = this;
    var oldCode = page.data.oldCode;
    var newCode = page.data.newCode;
    var passwordtest = /^[0-9a-zA-Z_]{6,16}$/
    if (!oldCode) {
      Common.Alert('修改提示', '请输入旧密码');
      return false;
    }
    if (!newCode) {
      Common.Alert('修改提示', '请输入新密码');
      return false;
    }
    if (!passwordtest.test(newCode)) {
      Common.Alert('修改提示', '新密码格式错误！');
      return false;
    }
    Common.my_request({
      url: '/AppMaster/Account/updateUserCode',
      data: {
        oldCode: oldCode,
        newCode: newCode
      },
      success: function (res) {
        if (res.data.result == 0) {
          wx.showToast({
            title: res.data.message,
            icon: 'success',
            duration: 2000
          });
          page.setData({
            oldCode: '',
            newCode: '',
          })
          page.modify();
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'success',
            duration: 2000
          });
          page.setData({
            oldCode: '',
          })
        }
      }
    });
  },
  timeHits: function () {
    var _this = this;
    var a;
    _this.setData({
      note: _this.data.note + 1,
    });
    //console.log(_this.data.note);
    if (_this.data.note == 1) {
      a = setTimeout(function () {
        //console.log(_this.data.note);
        if (_this.data.note >= 6) {
          wx.showModal({
            content: ApiUrl
          });
        }
        _this.setData({
          note: 0,
        });
      }, 20000);
    } else {
      if (_this.data.note >= 6) {
        wx.showModal({
          content: ApiUrl
        });
        _this.setData({
          note: 0,
        });
        clearTimeout(a);
      }
    }
  },
  showLogoutBtn: function () {
    var _this = this;
    var a;
    _this.setData({
      notel: _this.data.notel + 1,
    });
    if (_this.data.notel == 1) {
      a = setTimeout(function () {
        if (_this.data.notel >= 6) {
          _this.setData({
            showLogout: true
          })
        }
        _this.setData({
          notel: 0,
        });
      }, 20000);
    } else {
      if (_this.data.notel >= 6) {
        _this.setData({
          showLogout: true
        })
        _this.setData({
          notel: 0,
        });
        clearTimeout(a);
      }
    }
  },
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  },

  score(event) {
    const {
      is_none_user_img,
      is_none_user_name
    } = this.data
    if (wx.getStorageSync('user_id') < 0) {
      wx.navigateTo({
        url: '/pages/my/logintype/logintype?from=2'
      });
    } else {
      const {
        status
      } = event.currentTarget.dataset
      if (status) {
        wx.navigateTo({
          url: '/pages/score/index',
        })
      }
    }
  },
  userCenter() {
    const {
      isMember,
      level,
      logined
    } = this.data
    if (isMember && logined) {
      wx.navigateTo({
        url: '/subPage/member/index',
      })
    }
  },
  queryLevel() {
    Common.my_request({
      url: '/AppMaster/Notice/getNoticeList',
      data: {
        scene: 'user_center'
      },
      success: res => {
        const {
          data
        } = res.data
        if (data && data.length > 0) {
          const {
            new_lv
          } = data[0].data
          this.setData({
            showMember: true,
            member: {
              level: new_lv
            }
          })
        }
      }
    })
  },
  dinnerList() {
    wx.navigateTo({
      url: '/subPage/dinner/index',
    })
  },
  modalClick() {
    this.setData({
      showMember: false
    })
  },
  /**
   * 品鉴券
   */
  PJcoupon() {
    wx.navigateTo({
      url: '/subPage/tastingCoupon/index?from=0',
    })
  },
  modifyPwd() {
    wx.navigateTo({
      url: '/subPage/modifyPwd/index',
    })
  },
  goWholesale() {
    const {
      saleTypes
    } = this.data
    const {
      sale_type_switch_button,
      data
    } = saleTypes
    const {
      message,
      button_text
    } = data
    switch (sale_type_switch_button) {
      case 1:
        this.setData({
          tips: '确认切换到批发商城'
        })
        modal.showModal()
        break;
      case 2:
        wx.navigateTo({
          url: '/subPage/wholesale/index',
        })
        break;
      case 3:
        this.setData({
          tips: message,
          btnText: button_text
        })
        modal.showModal()
        break;
      case 4:
        this.setData({
          tips: message,
          btnText: button_text
        })
        modal.showModal()
        break;
      case 5:
        this.setData({
          tips: message,
          btnText: button_text
        })
        modal.showModal()
        break;
      case 11:
        this.setData({
          tips: button_text
        })
        modal.showModal()
        break;
      default:
        break;
    }
  },
  confirmHandler() {
    const {
      saleTypes
    } = this.data
    const {
      sale_type_switch_button
    } = saleTypes
    switch (sale_type_switch_button) {
      case 1:
        this.switchSaleType(2)
        break;
      case 3:
        wx.navigateTo({
          url: '/subPage/wholesale/index?type=3',
        })
        modal.hideModal()
        break;
      case 4:
        wx.switchTab({
          url: '/pages/product/index/index',
        })
        modal.hideModal()
        break;
      case 5:
        modal.hideModal()
        break;
      case 11:
        this.switchSaleType(1)
        break;
      default:
        break;
    }
  },
  /**
   * 切换销售模式
   * @param {number} type 1=零售 2=批发
   */
  switchSaleType(type) {
    SessionSellingServerUtil.switchSalesModel(type).then(jxbResp=>{
      modal.hideModal()
      // 初始化saleTypes
      //todo 待优化
      let saleTypes = this.data.saleTypes
      if(typeof saleTypes === 'undefined'){
        saleTypes = {
          data:{}
        }
      }
      if(typeof saleTypes.data === 'undefined'){
        saleTypes.data = {}
      }
      switch (type) {
        case 1:
          saleTypes.sale_type_switch_button = 1
          saleTypes.data.button_text = '切换批发'
          break;
        default:
          saleTypes.sale_type_switch_button = 11
          saleTypes.data.button_text = '切换零售'
          break;
      }
      this.setData({
        saleTypes: saleTypes
      })
      this.store.data.saleType = SessionUserUtil.getInstanceSync()._data.sale_type
      this.update()
      this.updateTheme()
    }).catch(err=>{
      console.log(err)
      InteractionUtil.showNotice(err.message)
    })
  },
  updateTheme() {
    getApp().getSaleMode()
  }
})